package com.zh.file.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.fdfs.ThumbImageConfig;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.zh.common.bean.Result;
import com.zh.file.common.utils.FileUtil;
import com.zh.file.common.utils.UUIDUtil;
import com.zh.file.config.UploadProperties;
import com.zh.file.entity.SysAppendix;
import com.zh.file.entity.SysAttachment;
import com.zh.file.mapper.SysAppendixMapper;
import com.zh.file.mapper.SysAttachmentMapper;
import com.zh.file.service.UploadFileService;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @ClassName UploadFileServiceImpl
 * @date: 2020.12.10 19:27
 * @Author: zhanghang
 */
@Service(value = "uploadFileService1")
public class UploadFileServiceImpl implements UploadFileService {
    @Autowired
    private SysAttachmentMapper sysAttachmentMapper;

    private final static Logger log = LoggerFactory.getLogger(UploadFileServiceImpl.class);
    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private SysAppendixMapper sysAppendixMapper;

    @Autowired
    private ThumbImageConfig thumbImageConfig;

    @Autowired
    private UploadProperties properties;

    @Override
    public Result<String> uploadFilesToServer(MultipartFile[] files, String fileType, String fileTypeCode) throws Exception {
            Result<String> result = new Result<>();
        String businessId = UUIDUtil.getUUID();
        List<SysAppendix> fileList = new ArrayList<>();
            try {
                for (int i = 0; i < files.length; i++) {
                    log.info("开始上传文件==============>{}", files[i].getOriginalFilename());
                    // 上传
                    StorePath storePath = null;
                    BufferedImage image = ImageIO.read(files[i].getInputStream());
                    if (image == null) {// 判断是否为图片
                        storePath = this.storageClient.uploadFile(files[i].getInputStream(), files[i].getSize(), FilenameUtils.getExtension(files[i].getOriginalFilename()), null);
                    } else {
                        storePath = storageClient.uploadImageAndCrtThumbImage(files[i].getInputStream(), files[i].getSize(), FilenameUtils.getExtension(files[i].getOriginalFilename()), null);
                        log.info("缩略图路径=========>{}", thumbImageConfig.getThumbImagePath(storePath.getPath()));
                    }
                    SysAppendix uploadFile = new SysAppendix();
                    uploadFile.setBusinessId(businessId);
                    // 不带分组的路径
                    uploadFile.setFilePath(storePath.getPath());
                    uploadFile.setGroupName(storePath.getGroup());
                    // 全路径
                    uploadFile.setPath(storePath.getFullPath());
                    uploadFile.setThumbImagePath(thumbImageConfig.getThumbImagePath(storePath.getPath()));
                    log.info("文件存储在服务器的路径==============>{}", properties.getBaseUrl() + storePath.getFullPath());
                    uploadFile.setCreateDate(new Date());
                    uploadFile.setFileName(files[i].getOriginalFilename());
                    uploadFile.setFileType(files[i].getOriginalFilename().substring(files[i].getOriginalFilename().indexOf(".")));
                    uploadFile.setCreateDate(new Date());
                    uploadFile.setFileSize(files[i].getSize());
                    uploadFile.setFileMd5(FileUtil.getFileMd5Value(storePath.getFullPath()));

                    if (image != null) {
                        log.info("缩略图路径=========>{}", thumbImageConfig.getThumbImagePath(storePath.getPath()));
                    }
                    log.info("文件上传服务器成功=========>{}", files[i].getOriginalFilename());
                    fileList.add(uploadFile);
                }

                Integer count = 0;
                fileList.forEach(append -> sysAppendixMapper.insert(append));
                SysAttachment item = new SysAttachment();
                item.setFileType(fileType);
                item.setFileTypeCode(fileTypeCode);
                item.setAppendixId(businessId);
                sysAttachmentMapper.insert(item);
                System.out.println(item.getId());
                result.setCode(200);
                result.setSuccess(true);


            } catch (Exception e) {
                log.info("文件上传失败 ==> ,{}" + e.getMessage());

                // fileList.clear();
                log.info("文件上传失败，正在清理文件==================>,{}", e.getMessage());
                result.setMessage("上传失败");
                result.setSuccess(false);
                e.printStackTrace();
                throw new Exception(e.getMessage());
            } finally {
                return result;
            }
        }

    /**
     * description: 文件下载
     * date: 2021年-01月-06日 14:37
     * author: zhanghang
     *
     * @param filesName
    * @param filesPath
    * @param response
     * @return void
     */
    @Override
    public void downloadFile(String filesName, String filesPath, HttpServletResponse response) throws IOException {
        // 这里的filesPath需要是这种格式的：M00/00/00/wKg7g1wN2YyAAH1MAADJbaKmScw004.jpg
        int length = properties.getGroupName().length();
        filesPath = filesPath.substring(properties.getGroupName().length() + 1);
        DownloadByteArray downloadByteArray = new DownloadByteArray();
        // 刚开始用的是DownloadFileWriter，结果得到bytes的字节数不对，导致下载后，文件打不开
        // DownloadFileWriter callback = new DownloadFileWriter(filesName);
        byte[] bytes = this.storageClient.downloadFile(properties.getGroupName(), filesPath, downloadByteArray);
        // 支持中文名称，避免乱码
        response.setContentType("application/force-download");
        response.addHeader("Content-Disposition", "attachment;fileName=" + new String(filesName.getBytes("UTF-8"), "iso-8859-1"));
        response.setCharacterEncoding("UTF-8");
        OutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
    }


    /**
     * description: 根据附件信息表主键删除文件
     * date: 2021年-01月-06日 14:42
     * author: zhanghang
     * 
     * @param id
     * @return void
     */ 
    @Override
    public void deleteFile(Long id) throws Exception {
        boolean b = false;
        SysAppendix file = sysAppendixMapper.selectById(id);
        if (file == null) {
            throw new RuntimeException("文件id:" + id + "数据库中不存在！");
        }
        storageClient.deleteFile(file.getPath());
        storageClient.deleteFile(file.getGroupName() + "/" + file.getThumbImagePath());
        b = true;
        if (b) {
            sysAppendixMapper.deleteById(id);
            System.out.println("删除文件成功");
        } else {
            System.out.println("删除文件失败");
            throw new RuntimeException("删除文件失败");
        }

    }

}
